package cn.golxen.blog.redis;

import cn.golxen.blog.commons.rabbitVo.AddRedisAvatarVo;
import cn.golxen.blog.commons.rabbitVo.AddRedisResumeVo;
import cn.golxen.blog.commons.rabbitVo.AddRedisSignatureVo;
import cn.golxen.blog.commons.rabbitVo.DeleteRedisByGenericKeyVo;
import cn.golxen.blog.mapper.AdminMapper;
import cn.golxen.blog.rabbitMQ.producer.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class AdminRedis {
    @Autowired
    @Qualifier(value = "taskExecutor")
    private ThreadPoolTaskExecutor poolTaskExecutor;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    Producer producer;

    public String getAvatar(){
        String avatar=redisTemplate.opsForValue().get("avatar");
        if (avatar!=null&&!avatar.isEmpty()){
            log.info("走redis");
        }else {
            log.info("走mysql");
            avatar=adminMapper.getAvatar();
            String finalAvatar = avatar;
            poolTaskExecutor.execute(()->{
                producer.adminProducer(new AddRedisAvatarVo(finalAvatar));
            });
        }
        return avatar;
    }
    public String getResume(){
        String resume=redisTemplate.opsForValue().get("resume");
        if (resume!=null&&!resume.isEmpty()){
            log.info("走redis");
        }else {
            log.info("走mysql");
            resume=adminMapper.getResume();
            String finalResume = resume;
            poolTaskExecutor.execute(()->{
                producer.adminProducer(new AddRedisResumeVo(finalResume));
            });
        }
        return resume;
    }
    public String getSignature(){
        String signature=redisTemplate.opsForValue().get("signature");
        if (signature!=null&&!signature.isEmpty()){
            log.info("走redis");
        }else {
            log.info("走mysql");
            signature=adminMapper.getSignature();
            String finalSignature = signature;
            poolTaskExecutor.execute(()->{
                producer.adminProducer(new AddRedisSignatureVo(finalSignature));
            });
        }
        return signature;
    }

    public void deleteByRedisKey(String delKey){
        producer.adminProducer(new DeleteRedisByGenericKeyVo(delKey));
    }

    public void flushDB(){
        log.info("清理redis");
        Set<String> keys = redisTemplate.keys("*");
        assert keys != null;
        redisTemplate.delete(keys);
    }
}
